package 力扣_树算法.遍历.层序遍历扩展;

import java.util.ArrayDeque;
import java.util.Deque;

/**116. 填充每个节点的下一个右侧节点指针
 * @author zx
 * @create 2022-04-13 11:03
 */
public class 填充每个节点的下一个右侧节点指针_116 {
    /**
     * @return 迭代(层序遍历)
     */
    public Node connect(Node root) {
        Deque<Node> queue = new ArrayDeque<>();
        if(root == null){
            return root;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            int levelCount = queue.size();
            for(int i = 0;i < levelCount;i++){
                Node node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                if(i != levelCount - 1){
                    node.next = queue.peek();
                }
            }
        }
        return root;
    }


    /**
     * @return 递归
     */
    public Node connect2(Node root) {
        if(root == null){
            return root;
        }
        helper(root);
        return root;
    }

    private void helper(Node root){
        if(root == null){
            return;
        }
        //连接同一父节点的左右节点
        if(root.left != null && root.right != null){
            root.left.next = root.right;
        }
        //连接不同父节点的右节点和左节点
        if(root.next != null && root.right != null){
            root.right.next = root.next.left;
        }
        connect(root.left);
        connect(root.right);
    }


    private class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
